﻿using Cinch;
using FR.SAFTAnalyser.Model;
using FR.SAFTAnalyser.Model.Stocks;
using FR.SAFTAnalyser.ViewModels.Pane;
using MEFedMVVM.Common;
using OfficeOpenXml;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FR.SAFTAnalyser.ViewModels
{
    public class StocksProductsViewModel : DocumentPartViewModel
    {
        public StocksProductsViewModel()
            : base("Stocks")
        {
            if (!Designer.IsInDesignMode)
            {
                Mediator.Instance.Register(this);

                DoOpenExcelCommand = new SimpleCommand<object, object>(CanOpenExcel, OpenExcel);
            }
        }

        internal override void ResetSaftFile()
        {
            this.Stocks = null;
        }

        #region Mediator messages
        [MediatorMessageSink(MessageType.STOCK_FILE_OPENED)]
        private void LoadInvoices(StockFile stock)
        {
            if (stock != null && stock.Stock != null)
                this.Stocks = stock.Stock;
        }
        #endregion

        #region Binding properties
        Stock[] stocks;
        public Stock[] Stocks
        {
            get
            {
                if (stocks == null && SAFT.StockAnalyser.Instance.StockFile != null)
                    stocks = SAFT.StockAnalyser.Instance.StockFile.Stock;

                return stocks;
            }
            set
            {
                stocks = value;
                NotifyPropertyChanged(ObservableHelper.CreateArgs<StocksProductsViewModel>(x => x.Stocks));

                if (stocks != null && string.IsNullOrEmpty(this.FilterStockProducts))
                {
                    DocNumberOfEntries = stocks.Length;

                    NotifyPropertyChanged(ObservableHelper.CreateArgs<StocksProductsViewModel>(x => x.DocNumberOfEntries));
                }
            }
        }

        string filterStockProducts;
        public string FilterStockProducts
        {
            get { return filterStockProducts; }
            set
            {
                filterStockProducts = value;

                if (string.IsNullOrEmpty(filterStockProducts))
                    this.Stocks = SAFT.StockAnalyser.Instance.StockFile.Stock;
                else
                {
                    var filter =
                        from s in SAFT.StockAnalyser.Instance.StockFile.Stock
                        where s.ProductCode.IndexOf(filterStockProducts, StringComparison.OrdinalIgnoreCase) >= 0 ||
                        s.ProductDescription.IndexOf(filterStockProducts, StringComparison.OrdinalIgnoreCase) >= 0 ||
                        s.ProductNumberCode.IndexOf(filterStockProducts, StringComparison.OrdinalIgnoreCase) >= 0 ||
                        s.UnitOfMeasure.IndexOf(filterStockProducts, StringComparison.OrdinalIgnoreCase) >= 0
                        select s;

                    this.Stocks = filter.ToArray();
                }
            }
        }

        public int DocNumberOfEntries { get; set; }
        #endregion

        #region Commands

        public SimpleCommand<object, object> DoOpenExcelCommand { get; private set; }
        private void OpenExcel(object args)
        {
            if (this.Stocks != null && this.Stocks.Length > 0)
            {
                DataTable dtStocks = new DataTable("Stocks");
                dtStocks.Columns.Add("Quantidade", typeof(decimal));
                dtStocks.Columns.Add("Tipo", typeof(string));
                dtStocks.Columns.Add("Identificador", typeof(string));
                dtStocks.Columns.Add("Descrição", typeof(string));
                dtStocks.Columns.Add("Código", typeof(string));
                dtStocks.Columns.Add("Unidade", typeof(string));

                foreach (Stock stock in this.Stocks)
                {
                    dtStocks.Rows.Add(
                        stock.ClosingStockQuantity,
                        stock.ProductCategory.ToString(),
                        stock.ProductCode,
                        stock.ProductDescription,
                        stock.ProductNumberCode,
                        stock.UnitOfMeasure);
                }

                ExcelPackage pck = new ExcelPackage();
                var wsEnum = pck.Workbook.Worksheets.Add("Stocks");
                //Load the collection starting from cell A1...
                wsEnum.Cells["A1"].LoadFromDataTable(dtStocks, true, TableStyles.Medium9);
                wsEnum.Cells[wsEnum.Dimension.Address].AutoFitColumns();

                //...and save
                var fi = new FileInfo(Path.GetTempPath() + Path.GetRandomFileName() + ".xlsx");

                pck.SaveAs(fi);

                Process.Start(fi.FullName);
            }
        }
        private bool CanOpenExcel(object args)
        {
            return this.Stocks != null && this.Stocks.Length > 0;
        }
        #endregion
    }
}
